﻿using System;
using System.Collections.Generic;
using Development.Network.Msg;
using System.Threading.Tasks;
using Development.Tools;

namespace Development.Network.MsgHandle
{
    /// <summary>
    /// 一种队列消息处理方式，保证消息同步处理
    /// </summary>
    public class MsgQueueHandle : MsgHandle
    {
        /// <summary>
        /// 消息队列
        /// </summary>
        private MsgQueue _msgQueue = null;
        private Task _runThread = null;
        private bool _isRun = false;

        public MsgQueueHandle(int startId, int endId)
            :base(startId,endId)
        {
            _msgQueue = new MsgQueue();
            _runThread = new Task(OnRun);
            _isRun = true;
            _runThread.Start();
        }

        public override void AddMsg(MsgPacket msg)
        {
            ///同步处理，直接扔到队列里面
            _msgQueue.EnQueue(msg);
        }

        /// <summary>
        /// 消息处理
        /// </summary>
        private void OnRun()
        {
            while(_isRun)
            {
                MsgPacket msg = _msgQueue.DeQueue();
                if(msg != null)
                {
                   long tickCount = Global.CurrTime();
                   ProcessMsg(msg);
                   long tempnow = Global.CurrTime();
                   if (tempnow - tickCount > 200)
                   {
                       Log.WriteLog(ELogLevel.LOG_INFO, "long loop :  msgs in " + (tempnow - tickCount).ToString() + "ms,msgId=" + msg.MsgId);
                   }
                }
                else
                {
                    ThreadUtils.Sleep(20);
                }
            }
        }

        public override void Release()
        {
            _isRun = false;
        }
    }
}
